<template>
  <div class="reception-announcement">
    <div class="header">
      <h2>公告管理</h2>
      <p>编辑发布系统公告和活动信息</p>
    </div>

    <!-- 公告列表 -->
    <el-card class="announcement-card">
      <template #header>
        <div class="card-header">
          <span>公告列表</span>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            发布公告
          </el-button>
        </div>
      </template>

      <el-table :data="announcements" v-loading="loading">
        <el-table-column prop="title" label="公告标题" width="200" />
        <el-table-column prop="content" label="公告内容" width="300" show-overflow-tooltip />
        <el-table-column prop="publishDate" label="发布时间" width="150" />
        <el-table-column prop="publisher" label="发布人" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '已发布' ? 'success' : 'warning'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isCarousel" label="轮播图" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isCarousel ? 'success' : 'info'">
              {{ row.isCarousel ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewAnnouncement(row)">
              查看
            </el-button>
            <el-button type="warning" link @click="editAnnouncement(row)" v-if="row.status === '草稿'">
              编辑
            </el-button>
            <el-button type="success" link @click="publishAnnouncement(row)" v-if="row.status === '草稿'">
              发布
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑公告对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="isEditing ? '编辑公告' : '发布公告'"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        ref="announcementFormRef"
        :model="announcementForm"
        :rules="announcementRules"
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
        </el-form-item>

        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
            @input="handleContentInput"
          />
        </el-form-item>

        <el-form-item label="AI润色">
          <el-button type="primary" @click="useAIAssistant" :loading="aiLoading">
            <el-icon><Magic /></el-icon>
            AI润色文案
          </el-button>
          <div class="ai-suggestions" v-if="aiSuggestions.length > 0">
            <h4>AI建议：</h4>
            <div class="suggestion-item" v-for="(suggestion, index) in aiSuggestions" :key="index">
              <p>{{ suggestion }}</p>
              <el-button type="primary" link @click="applySuggestion(suggestion)">
                应用此建议
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="公告类型" prop="type">
          <el-select v-model="announcementForm.type" placeholder="请选择公告类型">
            <el-option label="活动公告" value="活动公告" />
            <el-option label="系统通知" value="系统通知" />
            <el-option label="服务调整" value="服务调整" />
            <el-option label="节日祝福" value="节日祝福" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="轮播图展示" prop="isCarousel">
          <el-switch
            v-model="announcementForm.isCarousel"
            active-text="显示在首页轮播图"
            inactive-text="不显示"
          />
        </el-form-item>

        <el-form-item label="轮播图图片" v-if="announcementForm.isCarousel">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <img v-if="announcementForm.carouselImage" :src="announcementForm.carouselImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传 800x400 像素的图片</div>
        </el-form-item>

        <el-form-item label="模板选择" v-if="announcementForm.isCarousel">
          <el-select v-model="announcementForm.template" placeholder="请选择模板">
            <el-option label="活动宣传模板" value="activity" />
            <el-option label="节日祝福模板" value="festival" />
            <el-option label="服务介绍模板" value="service" />
            <el-option label="自定义模板" value="custom" />
          </el-select>
        </el-form-item>

        <el-form-item label="跳转链接" v-if="announcementForm.isCarousel">
          <el-input v-model="announcementForm.linkUrl" placeholder="请输入点击轮播图后跳转的链接" />
        </el-form-item>

        <el-form-item label="立即发布" prop="immediatePublish">
          <el-switch
            v-model="announcementForm.immediatePublish"
            active-text="立即发布"
            inactive-text="保存草稿"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAnnouncement" :loading="submitting">
            {{ isEditing ? '更新公告' : '发布公告' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="公告详情"
      width="600px"
    >
      <div class="announcement-detail" v-if="currentAnnouncement">
        <h3>{{ currentAnnouncement.title }}</h3>
        <div class="meta-info">
          <span>发布时间：{{ currentAnnouncement.publishDate }}</span>
          <span>发布人：{{ currentAnnouncement.publisher }}</span>
          <span>类型：{{ currentAnnouncement.type }}</span>
        </div>
        <div class="content">
          {{ currentAnnouncement.content }}
        </div>
        <div class="carousel-info" v-if="currentAnnouncement.isCarousel">
          <el-tag type="success">此公告显示在首页轮播图中</el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Magic } from '@element-plus/icons-vue'
import { 
  getAnnouncements, 
  createAnnouncement, 
  updateAnnouncement, 
  publishAnnouncement as publishAnnouncementApi,
  getAISuggestions 
} from '@/api/announcement'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const aiLoading = ref(false)
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const isEditing = ref(false)
const announcementFormRef = ref()
const currentAnnouncement = ref(null)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 公告列表
const announcements = ref([])

// AI建议
const aiSuggestions = ref([])

// 公告表单
const announcementForm = reactive({
  title: '',
  content: '',
  type: '活动公告',
  isCarousel: false,
  carouselImage: '',
  template: 'activity',
  linkUrl: '',
  immediatePublish: true
})

// 表单验证规则
const announcementRules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }]
}

// 加载公告列表
const loadAnnouncements = async () => {
  loading.value = true
  try {
    const response = await getAnnouncements({
      page: currentPage.value,
      size: pageSize.value
    })
    announcements.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载公告列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 查看公告详情
const viewAnnouncement = (announcement) => {
  currentAnnouncement.value = announcement
  showDetailDialog.value = true
}

// 编辑公告
const editAnnouncement = (announcement) => {
  isEditing.value = true
  Object.assign(announcementForm, announcement)
  showCreateDialog.value = true
}

// 发布公告
const publishAnnouncement = async (announcement) => {
  try {
    await ElMessageBox.confirm('确定要发布此公告吗？发布后无法撤回。', '提示', {
      type: 'warning'
    })
    
    await publishAnnouncementApi(announcement.announcementId)
    ElMessage.success('公告发布成功')
    loadAnnouncements()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败：' + error.message)
    }
  }
}

// 提交公告
const submitAnnouncement = async () => {
  if (!announcementFormRef.value) return
  
  try {
    await announcementFormRef.value.validate()
    submitting.value = true
    
    if (isEditing.value) {
      await updateAnnouncement(announcementForm)
      ElMessage.success('公告更新成功')
    } else {
      await createAnnouncement(announcementForm)
      ElMessage.success(announcementForm.immediatePublish ? '公告发布成功' : '公告保存为草稿')
    }
    
    showCreateDialog.value = false
    loadAnnouncements()
    resetAnnouncementForm()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败：' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 使用AI助手
const useAIAssistant = async () => {
  if (!announcementForm.content) {
    ElMessage.warning('请先输入公告内容')
    return
  }
  
  aiLoading.value = true
  try {
    const response = await getAISuggestions(announcementForm.content)
    aiSuggestions.value = response.data || []
    if (aiSuggestions.value.length === 0) {
      ElMessage.info('AI暂时没有更好的建议')
    }
  } catch (error) {
    ElMessage.error('AI助手调用失败：' + error.message)
  } finally {
    aiLoading.value = false
  }
}

// 应用AI建议
const applySuggestion = (suggestion) => {
  announcementForm.content = suggestion
  aiSuggestions.value = []
  ElMessage.success('已应用AI建议')
}

// 内容输入处理
const handleContentInput = () => {
  // 清空AI建议
  aiSuggestions.value = []
}

// 图片上传前检查
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理图片上传
const handleAvatarUpload = (options) => {
  // 模拟上传成功
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    announcementForm.carouselImage = e.target.result
    ElMessage.success('图片上传成功')
  }
  reader.readAsDataURL(file)
}

// 重置表单
const resetAnnouncementForm = () => {
  Object.assign(announcementForm, {
    title: '',
    content: '',
    type: '活动公告',
    isCarousel: false,
    carouselImage: '',
    template: 'activity',
    linkUrl: '',
    immediatePublish: true
  })
  aiSuggestions.value = []
  isEditing.value = false
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadAnnouncements()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadAnnouncements()
}

// 对话框关闭处理
const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的数据将丢失。')
    .then(() => {
      resetAnnouncementForm()
      done()
    })
    .catch(() => {
      // 取消关闭
    })
}

// 生命周期
onMounted(() => {
  loadAnnouncements()
})
</script>

<style scoped>
.reception-announcement {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.announcement-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.ai-suggestions {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.ai-suggestions h4 {
  margin: 0 0 10px 0;
  color: #606266;
}

.suggestion-item {
  margin-bottom: 10px;
  padding: 8px;
  background-color: white;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.suggestion-item p {
  margin: 0 0 5px 0;
  color: #606266;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 178px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.announcement-detail h3 {
  margin: 0 0 15px 0;
  color: #303133;
}

.meta-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.meta-info span {
  margin-right: 20px;
  color: #606266;
  font-size: 14px;
}

.content {
  line-height: 1.6;
  color: #606266;
}

.carousel-info {
  margin-top: 15px;
}
</style>
